package org.xx.armory.spring5.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 使用Jdbc的验证器。
 */
public class JdbcAuthenticationProvider
        extends AbstractArmoryUserPasswordAuthenticationProvider
        implements AuthenticationProvider {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JdbcAuthenticationDao jdbcAuthenticationDao;

    @Override
    protected Collection<? extends GrantedAuthority> authenticate(
            String username,
            CharSequence password,
            ArmoryWebAuthenticationDetails details
    ) {
        final var hashed = this.jdbcAuthenticationDao.loadHashedPasswordByUsername(username);
        if (!this.passwordEncoder.matches(password, hashed)) {
            throw new BadCredentialsException("Username and password mismatched");
        }

        return this.jdbcAuthenticationDao.loadAuthoritiesByUsername(username)
                                         .stream()
                                         .map(SimpleGrantedAuthority::new)
                                         .collect(Collectors.toSet());
    }
}
